package com.mlnx.bluwifi.service.iml;

import com.mlnx.device.entity.Device;
import com.mlnx.device.service.DeviceService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by amanda.shan on 2019/12/2.
 */
public class BaseWifiBluService {

    @Autowired
    private DeviceService deviceService;

    private Map<String, Device> deviceMap = new ConcurrentHashMap<>();

    @Scheduled(cron = "*/5 * * * * ?")  // 每隔5s执行一次
    public void renewPatientId() {
        Set<String> deviceIds = deviceMap.keySet();
        if (deviceIds.size() > 0) {
            Map<String, Device> tempDeviceMap = deviceService.getDeviceMap(deviceIds);

            for (String deviceId : tempDeviceMap.keySet()) {
                deviceMap.put(deviceId, tempDeviceMap.get(deviceId));
            }
        }
    }

    public Device getDevice(String deviceId) {
        Device device = deviceMap.get(deviceId);

        if (device == null) {
            device = deviceService.getDevice(deviceId);
            if (device != null) {
                deviceMap.put(deviceId, device);
            }
        }
        return device;
    }
}
